﻿using System;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Bronze.Components;
using BSF.Enums;
using BSF.ServicesResult;

namespace HuntingFishGame.CustomerApi
{
    /// <summary>
    /// 验证用户访问Api的合法性
    /// </summary>
    [AttributeUsage(AttributeTargets.Method, Inherited = true)]
    public class ValidTokenAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public ValidTokenAttribute()
        {
        }



        /// <summary>
        /// api controller 访问拦截器
        /// 集成权限验证，数据库访问，日志记录，错误拦截，api约定输出
        /// </summary>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            ApiResult apiResult = null;           
            
            #region 获取token对应的用户信息

            var user = ApiUtils.GetTokenUserInfo(actionContext.Request, ref apiResult);
            
            #endregion
            #region 耗时日志，限流，跨域
            /*
            //耗时日志
            TimeWatchLog watch = new TimeWatchLog();
                       
            #region 初始耗时参数绑定
            var _req = CommonHelper.GetRequest();//获取请求
            var paramBinds = new ParamBinds();
            string url = "";
            if (_req != null)
                url = _req.RawUrl;
            CommonHelper.ParamBinds(_req, ref paramBinds);
            paramBinds.RequseUrl = url;
            #endregion

            int dqbm = LibConvert.StrToInt(_req["dqbm"]);
            int configAreaCode = CommonHelper.GetDqbmForConfig(dqbm);
            //获取控制器
            //var currcontroller = actionContext.ControllerContext.Controller;
            string caction = actionContext.ControllerContext.RouteData.Route.RouteTemplate;
      
            #region  限流相关代码 用户缓解压力
            if (configAreaCode != 0)
            {
                string isOpenRestrictor = new HuntingFishGame.Core.SystemConfig.tb_system_config_dal().GetCache(SnsProcessConfig.IsOpenRestrictor, configAreaCode);
                if (isOpenRestrictor == "true")
                {
                    IOnlineUser usertoken = actionContext.Request.Properties["Token_UserInfo"] as IOnlineUser;
                    string restrictorController = new HuntingFishGame.Core.SystemConfig.tb_system_config_dal().GetCache(SnsProcessConfig.RestictorControllerRule, configAreaCode);
                    if (CommonHelper.ValidateRestrictorController(string.Empty, caction, restrictorController))
                    {
                        string restrictorRule = new HuntingFishGame.Core.SystemConfig.tb_system_config_dal().GetCache(SnsProcessConfig.RestrictorRule, configAreaCode);
                        bool restrictor = false;
                        if (usertoken == null || string.IsNullOrWhiteSpace(usertoken.FUserId.ToString()))
                        {
                            //限流尾号包含-1,则未登陆用户限流
                            if (restrictorRule.IndexOf("-1") != -1)
                            {
                                restrictor = true;
                            }
                        }
                        else
                        {
                            char num = usertoken.FUserId.ToString().Last();//取用户手机号(可以大数据分析哪部分尾号的用户不活跃，或者用户数较少)，这里暂时取的是用户id
                            if (restrictorRule.IndexOf(num) != -1)//用户尾号限流
                            {
                                restrictor = true;
                            }
                        }
                        if (restrictor)
                        {
                            //json.Data = new ServiceResult() { code = (int)BSFAPICode.NormalError, msg = "亲，活动太火爆了，需排队进入哦~好东西值得等待", total = 0 };
                            //return json;
                        }
                    }
                }
            }
            #endregion

            watch.Write(paramBinds);//打印耗时日志

            #region 跨域请求返回(增加模块)
            int crossdomain = LibConvert.ObjToInt(HuntingFishGame.Core.Extensions.RequestMethodHelper.RequestParamValue(_req, "crossdomain"));
            if (crossdomain == 1)
            {
                string jsons = Newtonsoft.Json.JsonConvert.SerializeObject(apiResult);
                var response = System.Web.HttpContext.Current.Response;
                response.ContentType = "text/html";
                response.Charset = "utf-8";//设置输出流的字符集-中文
                response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流的字符集
                //获取回调函数名
                var context = System.Web.HttpContext.Current.Request;
                string callback = context.QueryString["success_jsonpCallback"];
                response.Write(callback + "(" + jsons + ")");
                response.End();

                //return new JsonpResult { Data = jsons };  //返回 jsonp 数据，输出回调函数
            }
            #endregion
            */
            #endregion

            //返回错误信息
            if (apiResult != null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, apiResult);
            }
        }

    }
}